package csc.daonjpa.java.transaction;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import csc.daonjpa.java.controller.EntityManagerFactoryUtil;

/**
 * Class to mange jpa transaction.
 * @author tnguyen256
 *
 */
public class TransactionManager {
	private static final EntityManagerFactory emf;
	private static final ThreadLocal<EntityManager> threadLocal;
	static {
		emf = EntityManagerFactoryUtil.getEntityManagerFactory();
		threadLocal = new ThreadLocal<EntityManager>();
	}

	public static EntityManager getEntityManager() {
		EntityManager em = threadLocal.get();

		if (em == null) {
			em = emf.createEntityManager();
			threadLocal.set(em);
		}
		return em;
	}

	public static void close() {
		EntityManager em = threadLocal.get();
		if (em != null) {
			em.close();
			threadLocal.set(null);
		}
	}

	public static void closeEntityManagerFactory() {
		emf.close();
	}

	public static void begin() {
		getEntityManager().getTransaction().begin();
	}

	// This may not be called
	public static void rollback() {
		if (getEntityManager().getTransaction().isActive()) {
			getEntityManager().getTransaction().rollback();
		}
	}

	public static void commit() {
		// Spring handles exceptions already so we may have to rollback in this method.
		if (getEntityManager().getTransaction().getRollbackOnly()) {
			rollback();
		} else {
			getEntityManager().getTransaction().commit();
		}
	}
}
